#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define NAME "fifo"
#define PATH "."

class Fifo
{
public:
    Fifo(std::string path, std::string name)
        : _name(name), _path(path)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        // 新建管道
        _n = mkfifo(_fifoname.c_str(), 0666);
        if (_n < 0)
        {
            std::cerr << "创建管道失败" << std::endl;
            exit(1);
        }
        else
        {
            std::cout << "创建管道成功!" << std::endl;
        }
    }

    ~Fifo()
    {
        if (_n > 0)
            // 销毁管道
            unlink(_fifoname.c_str());
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _n;
};

class Openfifo
{
public:
    Openfifo(std::string path, std::string name)
        : _name(name), _path(path)
    {
        _filename = path + "/" + name;
    }

    ~Openfifo()
    {
        
    }

    void Open_for_write()
    {
        // 打开管道
         _fd = open(_filename.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "打开管道失败!" << std::endl;
            exit(1);
        }
        else
        {
            std::cout << "打开管道成功" << std::endl;
        }
    }

    void open_for_read()
    {
        // 打开管道
         _fd = open(_filename.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "打开管道失败!" << std::endl;
            exit(1);
        }
        else
        {
            std::cout << "打开管道成功" << std::endl;
        }
    }

    void Write()
    {
        std::string str;
        while (1)
        {
            
            std::cout << "Please input:";
            getline(std::cin, str);
            write(_fd, str.c_str(), str.size());
        }
    }

    void Read()
    {
        while (1)
        {
            // 读取管道内数据
            char buffer[1024];
            int ret = read(_fd, buffer, sizeof(buffer));
            if (ret > 0)
            {
                buffer[ret] = 0;
                std::cout << "client say:" << buffer << std::endl;
            }
            else if (ret == 0)
            {
                std::cout << "client quit!" << std::endl;
                return;
            }
            else
            {
                std::cerr << "read cerror" << std::endl;
            }
        }
    }


    void Close()
    {
        close(_fd);

    }
private:
    std::string _path;
    std::string _name;
    std::string _filename;
    int _fd;
};
